<?php

namespace EasyVote\EasyVoteBundle\Controller;

use EasyVote\EasyVoteBundle\Entity\Profile;
use EasyVote\EasyVoteBundle\Entity\Classification;
use EasyVote\EasyVoteBundle\Entity\Email;
use EasyVote\EasyVoteBundle\Entity\Degree;
use EasyVote\EasyVoteBundle\Form\Type\ProfileType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use EasyVote\EasyVoteBundle\Repository\UserRepository;

/**
 * Class ProfileController
 * Handles all views and database entities concerning user profiles.
 * @package EasyVote\EasyVoteBundle\Controller
 */
class ProfileController extends Controller
{
    /**
     * @Template
     * Used to show a user profile page.
     * @param int $id The id of the user to show
     * @return array The user entity of the id
     */
    public function showAction($id)
    {
        $data = array(); 
        
		// Find the user with an id of $id in the Database
		$em = $this->getDoctrine()->getManager();
		$userRepo = $em->getRepository('EasyVoteBundle:User');
        $data['user'] = $userRepo->findOneById($id);
        
		// Use the profile of the current user if the user doesn't exist        
        if ($data['user'] == null) {
			$data['user'] = $this->getUser();
		}
        
        // Is this profile for the current user
        if ($this->getUser() == $data['user']) {
			$data['isCurrentUser'] = true;			
		}
        else {
			$data['isCurrentUser'] = false;						
		}
		
		// Is current user an admin
		$data['isAdmin'] = $this->getUser()->isAdmin();
		
		// Return true if the user needs to update their profile
		$data['isProfileComplete'] = UserRepository::isProfileComplete($this->getUser()->getProfile());

        return $data;
    }

    /**
     * @Template
     * Used to edit a profile page. The title of the profile of a user
     * is always the user's display name.
     * @param Request $request
     * @param $id The ID of the profile to edit
     * @return Response The form to edit the profile page, or redirects to the
     *         profile page if the form has been submitted.
     */
    public function editAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

		// Make sure that this is the current user or an admin
		$userRepo = $em->getRepository('EasyVoteBundle:User');
        $accessUser = $userRepo->findOneById($id);		
		
        // Retrieve user information
        $user = $this->getUser();
        
        // Immediately return if this is not the current user or an admin
        if ($accessUser != $user && !$this->getUser()->isAdmin()) {
			return $this->redirect($this->generateUrl('profile_show', array('id' => $id)));
		}

        // Is current user an admin
        $isAdmin = $this->getUser()->isAdmin();

        // Create the form
        $form = $this->createFormBuilder()
			->add('displayName', 'text', array(
					'data' => $user->getDisplayName()
				)
			)
			->add('addEmail', 'email', array(
					'required' => false
				)
			)
			->add('removeEmail', 'entity', array(
					'required' => false, 
					'empty_data' => null, 
					'empty_value' => 'Choose an option', 
					'class' => 'EasyVoteBundle:Email', 
					'property' => 'value', 
					'multiple' => true,
					'choices' => $user->getEmails()
				)
			)
			->add('gender', 'entity', array(
					'class' => 'EasyVoteBundle:Gender', 
					'property' => 'name', 
					'data' => $user->getGender(), 
					'empty_value' => 'Choose an option', 
					'multiple' => false
				)
			)
			->add('classification', 'entity', array(
					'class' => 'EasyVoteBundle:Classification',
					'property' => 'name',
					'data' => $user->getClassification(),
					'empty_value' => 'Choose an option',
					'multiple' => false
				)
			)
			->add('addDegree', 'entity', array(
					'required' => false,
					'class' => 'EasyVoteBundle:Degree', 
					'property' => 'displayName',
					'empty_value' => 'Choose degree',
					'multiple' => false
				)
			)
			->add('removeDegree', 'entity', array(
					'required' => false, 
					'empty_data' => null, 
					'empty_value' => 'Choose an option', 
					'choices' => $user->getDegrees(),
					'class' => 'EasyVoteBundle:Degree', 
					'property' => 'displayName', 
					'multiple' => true,
				)
			)
			->add('addJob', 'entity', array(
					'required' => false,
					'empty_data' => null,
					'class' => 'EasyVoteBundle:Job',
					'property' => 'name',
					'empty_value' => 'Choose an option', 
					'multiple' => false
				)
			)
			-> add('removeJob', 'entity', array(
					'required' => false,
					'empty_data' => null,
					'class' => 'EasyVoteBundle:Job',
					'choices' => $user->getJobs(), 
					'property' => 'name',
					'empty_value' => 'Choose an option',
					'multiple' => true
				)
			)
			// profile stuff
			/*
			->add('title', 'text', array(
					'data' => $user->getProfile()->getTitle()
				)
			)
			*/
			->add('profilePicture', 'url', array(
					'data' => $user->getProfile()->getPicture()
				)
			)
			->add('summary', 'text', array(
					'data' => $user->getProfile()->getSummary()
				)
			)
			->add('fullText', 'textarea', array(
					'data' => $user->getProfile()->getFtext()
				)
			)
            ->add('save', 'submit', array('label' => 'Save'))
            ->getForm();
            
        //this block has "what to do if form is being submitted"
        if ($request->getMethod() == 'POST') 
        {
            $form->handleRequest($request);

            if ($form->isValid()) 
            {
                // Saves the profile to the database
				$data = $form->getData();
				
				if ($data['displayName'] != null) 
				{					
					if (!empty($data['displayName'])) 
					{
						$user->setDisplayName($data['displayName']);
						$user->getProfile()->setTitle($data['displayName']);
					}
				}
				
				if ($data['addEmail'] != null) 
				{
					if (!empty($data['addEmail'])) 
					{
						// Create new email object
						$emailToAdd = new Email();
						$emailToAdd->setValue($data['addEmail']);
							
						// Add email to the user and persist the email to the database
						$user->addEmail($emailToAdd);
						$em->persist($emailToAdd);	
						$em->flush();
					}
				}
				if ($data['removeEmail'] != null) 
				{
					if (!empty($data['removeEmail'])) 
					{
						foreach ($data['removeEmail'] as $item) 
						{
							$user->removeEmail($item);
							$em->persist($user);
							$em->flush();
							$em->remove($item);
						}
					}
				}
				if ($data['gender'] != null) 
				{					
					if (!empty($data['gender'])) 
					{
						$user->setGender($data['gender']);
					}
				}
				if ($data['classification'] != null) 
				{					
					if (!empty($data['classification'])) 
					{
						$user->setClassification($data['classification']);
					}
				}
				if ($data['addDegree'] != null) 
				{
					if (!empty($data['addDegree'])) 
					{
						$user->addDegree($data['addDegree']);
						$em->persist($user);
						$em->flush();
					}
				}
				if ($data['removeDegree'] != null) 
				{
					if (!empty($data['removeDegree'])) 
					{
						foreach ($data['removeDegree'] as $item) 
						{
							$user->removeDegree($item);
							$em->persist($user);
							$em->flush();
							$em->remove($item);
						}						
					}
				}
				/*
				if ($data['title'] != null) 
				{
					if (!empty($data['title']) != null) 
					{
						$user->getProfile()->setTitle($data['title']);
					}
				}
				*/
				if ($data['profilePicture'] != null) 
				{
					if (!empty($data['profilePicture'])) 
					{
						$user->getProfile()->setPicture($data['profilePicture']);
					}
				}
				if ($data['summary'] != null) 
				{
					if (!empty($data['summary'])) 
					{
						$user->getProfile()->setSummary($data['summary']);
					}
				}
				if ($data['fullText'] != null) 
				{
					if (!empty($data['fullText'])) 
					{
						$user->getProfile()->setFtext($data['fullText']);
					}
				}
				
				// Save information to the database
                $em->persist($user);
                $em->flush();

                // Redirect back to the profile page
                return $this->redirect($this->generateUrl('profile_show', array('id' => $id, 'isAdmin' => $isAdmin)));
            }
        }
        
        // Render the form
		return $this->render('EasyVoteBundle:Profile:edit.html.twig', array('form' => $form->createView(), 'isAdmin' => $isAdmin));
    }
}
